package com.weitu.base.controller;

import com.weitu.permission.department.entity.Department;
import com.weitu.permission.log.entity.LoginLog;
import com.weitu.permission.log.service.LogService;
import com.weitu.permission.user.entity.User;
import com.weitu.permission.user.entity.UserDepartment;
import com.weitu.permission.user.service.UserService;
import com.weitu.util.AjaxResult;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author LiMeng 2017/3/13
 */
@Controller
@RequestMapping(value = "/")
public class LoginController extends BaseController {

    private static final String MODULE_BATH_PATH = BASE_JSP_PATH + "permission";

    private final LogService logService;

    private final UserService userService;

    @Autowired
    public LoginController(LogService logService, UserService userService) {
        this.logService = logService;
        this.userService = userService;
    }

    /**
     * 跳转到登录页面,get提交时执行
     *
     * @param request request
     * @return login页面
     */
    @RequestMapping(value = "login", method = RequestMethod.GET)
    public String login(HttpServletRequest request) {
        request.removeAttribute("error");
        return "login";
    }

    /***
     * 系统登录方法
     * @param userName 用户名
     * @param password 密码
     * @return login页面
     */
    @ResponseBody
    @RequestMapping(value = "login", method = RequestMethod.POST)
    public AjaxResult login(String userName, String password) throws Exception {

        AjaxResult ajaxResult = new AjaxResult();

        UsernamePasswordToken token = new UsernamePasswordToken(userName, password);

        boolean success;
        String message;
        User loginUser = null;


        try {
            //执行 Shiro 用户密码认证
            Subject user = SecurityUtils.getSubject();
            user.login(token);
            //根据userName 获得用户的数据放入session
            loginUser = userService.selectByUserName(userName);
            success = true;
            message = "登录成功！";
        } catch (LockedAccountException e) {//账号锁定异常
            token.clear();
            success = false;
            message = "用户已经被锁定不能登录，请与管理员联系！";

        } catch (ExcessiveAttemptsException e) {//登录失败次数过多异常
            token.clear();
            success = false;
            message = "账号：" + userName + " 登录失败次数过多,锁定10分钟!";

        } catch (AuthenticationException e) {//用户名密码错误异常
            token.clear();
            success = false;
            message = "用户名或密码不正确！";
        }
        ajaxResult.setSuccess(success);
        ajaxResult.setMessage(message);

        //获得用户部门
        if (loginUser != null) {
            List<UserDepartment> userDepartmentList = loginUser.getUserDepartmentList();

            //默认使用第一个用户登录
            if (!userDepartmentList.isEmpty()) {
                UserDepartment userDepartment = userDepartmentList.get(0);
                String deptId = userDepartment.getDeptId();
                String deptName = userDepartment.getDeptName();
                Department department = new Department();
                department.setId(deptId);
                department.setName(deptName);
                loginUser.setDepartment(department);
            }

            Session session = SecurityUtils.getSubject().getSession();

            session.setAttribute("loginUser", loginUser);

            LoginLog loginLog = new LoginLog();
            loginLog.setLoginUserId(loginUser.getId());
            loginLog.setRemarks(message);
            loginLog.setLoginIp(session.getHost());
            //插入登录日志
            logService.insertLoginLog(loginLog);
            //日志Id保存到session
            session.setAttribute("loginLogId", loginLog.getId());
        }
        return ajaxResult;
    }

    @ResponseBody
    @RequestMapping(value = "logout", method = RequestMethod.GET)
    public ModelAndView logout() throws Exception {

        ModelAndView modelAndView = new ModelAndView();

        modelAndView.setViewName("redirect:login.shtml");

        SecurityUtils.getSubject().logout();

        return modelAndView;
    }

}